package com.party.web.web.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.commune.CAdminBranch;
import com.party.core.model.member.MemberBank;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PackageCount;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.service.commune.ICAdminBranchService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberBankService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.util.MemberFormUtil;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.sign.IMemberSignService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.pay.PayPcOrderBizService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.biz.system.member.RoleBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.input.system.SelectMemberInput;
import com.party.web.web.dto.input.user.UpdateRefundPwdInput;
import com.party.web.web.dto.input.verifyCode.VerifyCodeInput;
import com.party.core.model.member.MemberGroupOutput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.util.*;

/**
 * @ClassName MemberGroupController
 * @Description 机构用户
 * @Author yifeng
 * @Date 2019/9/11 9:28
 **/
@Controller
public class MemberGroupController {

    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private IMemberBankService memberBankService;
    @Autowired
    private IMemberPartnerService memberPartnerService;
    @Autowired
    private PayPcOrderBizService savePackageCountBiz;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberSetService memberSetService;
    @Autowired
    private IMemberSignService memberSignService;
    @Autowired
    private RoleBizService roleBizService;
    @Autowired
    private ICAdminBranchService adminBranchService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;

    private Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 子账号列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @return
     * @author yifeng
     * @date 10:05 2019/9/11
     **/
    @RequestMapping(value = "member/group/childList")
    public ModelAndView childList(MemberGroup member, Page page, CommonInput commonInput, String partnerId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childList");
        try {
            page.setLimit(20);
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();
            String memberGroupId = currentUser.getId();
            if (StringUtils.isEmpty(partnerId)) {
                partnerId = null;
            }

            if (currentUser.isXzgsAdmin()) { // 管理员账号
                memberGroupId = currentUser.getPartnerId();
            }
            if (StringUtils.isNotEmpty(partnerId)) {
                memberGroupId = partnerId;
            }
            params.put("partnerId", memberGroupId);


            member.setIsPartner(1);
            List<MemberGroupOutput> members = memberGroupService.childListPage(member, params, page);
            for (MemberGroupOutput mg : members) {
                //个人资料二维码
                String filePath = fileBizService.getUploadCIPath(mg.getId(), "integralPartnerRecommend");
                String url = cosBizService.getPreviewPictureUrl(filePath + mg.getId());
                mg.setChildInviteQrCode(url);
            }


            mv.addObject("partnerId", partnerId);
            mv.addObject("memberGroupId", currentUser.getId());
            mv.addObject("xzgsId", memberGroupBizService.getXzgsMemberId());
            mv.addObject("isChild", currentUser.isChild());
            mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
            mv.addObject("members", members);
            mv.addObject("member", member);
            mv.addObject("page", page);
            mv.addObject("input", commonInput);
        } catch (Exception e) {
            logger.error("合作商列表异常", e);
        }
        return mv;
    }


    /**
     * 子账号列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @return
     * @author yifeng
     * @date 10:05 2019/9/11
     **/
    @RequestMapping(value = "member/group/childListBackUp")
    public ModelAndView childListBackUp(MemberGroup member, Page page, CommonInput commonInput, String partnerId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childList");
        String xzgsMemberId = memberGroupBizService.getXzgsMemberId();

        try {
            page.setLimit(20);
            member.setIsPartner(1);
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();

            if (xzgsMemberId.equals(currentUser.getId())) {
                mv.addObject("isXzgsAccount", true);
                mv.addObject("xzgsId", xzgsMemberId);
            }
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            params.put("partnerId", currentUser.getId());
            //点击进入的不是一级子账号
            mv.addObject("oneLevelChild", false);
            if (StringUtils.isNotEmpty(partnerId)) {
                params.put("partnerId", partnerId);
                boolean isXZSG = sysRoleService.hasRole(partnerId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());

                mv.addObject("oneLevelChild", true);
                mv.addObject("partnerId", partnerId);
                mv.addObject("distributionRole", true);
                mv.addObject("isXZSG", isXZSG);
            }

            if (StringUtils.isEmpty(currentUser.getPartnerId())) {
                boolean isXZSG = sysRoleService.hasRole(currentUser.getId(), RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
                mv.addObject("isChild", false);
                mv.addObject("isXZSG", isXZSG);
            } else {
                //当前登录是一级子账号
                boolean resutle = sysRoleService.hasRole(currentUser.getId(), RoleEnum.ONE_LEVEL_CHILD.getCode());
                boolean isXZSG = sysRoleService.hasRole(currentUser.getId(), RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
                if (resutle) {
                    mv.addObject("oneLevelChild", true);
                    mv.addObject("partnerId", currentUser.getId());
                    mv.addObject("distributionRole", true);
                    mv.addObject("isXZSG", isXZSG);
                }
            }

            List<MemberGroupOutput> members = memberGroupService.childListPage(member, params, page);
            mv.addObject("members", members);
            mv.addObject("member", member);
            mv.addObject("page", page);
            mv.addObject("input", commonInput);
        } catch (Exception e) {
            logger.error("合作商列表异常", e);
        }
        return mv;

    }

    /**
     * 管理员列表
     *
     * @param member
     * @param page
     * @param commonInput
     * @return
     * @author yifeng
     * @date 10:05 2019/9/11
     **/
    @RequestMapping(value = "member/group/adminList")
    public ModelAndView adminList(MemberGroup member, Page page, CommonInput commonInput, String partnerId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/adminList");
        try {
            page.setLimit(20);
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            member.setType(Constant.MEMBER_XZGSADMIN);
            List<MemberGroup> members = memberGroupService.webListPage(member, params, page);
            mv.addObject("members", members);
            mv.addObject("member", member);
            mv.addObject("page", page);
            mv.addObject("input", commonInput);
        } catch (Exception e) {
            logger.error("管理员列表异常", e);
        }
        return mv;

    }

    /**
     * 编辑管理员
     *
     * @return
     * @author yifeng
     * @date 11:02 2019/9/11
     **/
    @RequestMapping(value = "member/group/adminForm")
    public ModelAndView adminForm(String id) {
        ModelAndView mv = new ModelAndView("system/memberGroup/xzgsAdminForm");
        MemberGroup member = null;
        if (StringUtils.isNotEmpty(id)) {
            member = memberGroupService.get(id);
        }
        mv.addObject("member", member);
        mv.addObject("partnerName", memberGroupService.get(RealmUtils.getCurrentUser().getId()).getRealname());
        return mv;
    }

    /**
     * 保存管理员
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/saveAdmin")
    public AjaxResult saveAdmin(MemberGroup member) {
        try {
            memberGroupBizService.saveAdminBiz(member);
        } catch (Exception e) {
            logger.error("管理员保存异常", e);
            return AjaxResult.error("用户保存异常");
        }
        return AjaxResult.success("保存成功");
    }


    /**
     * 编辑资料
     *
     * @return
     * @author yifeng
     * @date 11:02 2019/9/11
     **/
    @RequestMapping(value = "member/group/childForm")
    public ModelAndView childForm(String from, String id, String partnerId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/childForm");
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(partnerId)) {
            id = RealmUtils.getCurrentUser().getId();
        }
        MemberGroup member = memberGroupService.get(id);
        if (StringUtils.isEmpty(partnerId)) {
            mv.addObject("member", member);
            mv.addObject("partnerName", member.getRealname());
        } else {
            MemberGroup partner = memberGroupService.get(partnerId);
            mv.addObject("partnerId", partnerId);
            mv.addObject("partnerName", partner.getRealname());
        }
        mv.addObject("from", from);
        return mv;
    }

    /**
     * 保存子账号
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/saveChild")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveChild(MemberGroup member, String partnerId) {

        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                memberGroupBizService.savePartnerBiz(member);

                try {
                    memberGroupBizService.getChildInviteQrCode(member.getId());
                } catch (Exception e) {
                    logger.error("生成分社邀请二维码异常", e);
                }
                return AjaxResult.success("资料编辑成功");
            }

            if (StringUtils.isEmpty(member.getId()) && StringUtils.isNotEmpty(partnerId)) {
                memberGroupBizService.checkAccountInfo(member);
                member.setPartnerId(partnerId);
                member.setPartnerIds(partnerId);
                memberGroupBizService.savePartnerBiz(member);

                String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
                if (xzgsMemberId.equals(partnerId)) {
                    new Thread(() -> {
                        //行知公社创建一级子账号的时候初始化圈子和相册
                        logger.info("开始初始化相册和圈子....");
                        memberGroupBizService.initCricleAndPhoto(member);
                    }).start();
                    try {
                        memberGroupBizService.getChildInviteQrCode(member.getId());
                    } catch (Exception e) {
                        logger.error("生成分社邀请二维码异常", e);
                    }
                }

                memberSetService.initMemberSet(member.getId());
                // 保存合作商附属表  机构app签到
                memberSignService.getSet(member.getId());

                MemberPartner memberPartner = memberPartnerService.findByMemberId(member.getId());
                if (null == memberPartner) {
                    MemberPartner partner = memberPartnerService.findByMemberId(partnerId);
                    memberPartner = new MemberPartner();
                    memberPartner.setMemberId(member.getId());
                    memberPartner.setCreateBy(member.getId());
                    memberPartner.setUpdateBy(member.getId());
                    memberPartner.setPartnerRemark(partner.getPartnerRemark());
                    memberPartner.setPartnerType(partner.getPartnerType());
                    memberPartner.setSystemType(partner.getSystemType());
                    memberPartnerService.insert(memberPartner);
                }
            }

            return AjaxResult.success("添加成功");
        } catch (Exception e) {
            logger.error("子账号添加异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("子账号添加异常");
        }

    }

    /**
     * 修改退款密码
     *
     * @param updateRefundPwdInput
     * @param result
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/updateRefundPwd")
    public AjaxResult updateRefundPwd(@Validated UpdateRefundPwdInput updateRefundPwdInput, BindingResult result, String id) {
        try {
            AjaxResult ajaxResult = new AjaxResult();
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            if (StringUtils.isNotEmpty(id)) {
                MemberGroup t = memberGroupService.get(id);
                String old = updateRefundPwdInput.getOldPassword();
                if (StringUtils.isNotEmpty(old)) {
                    if (StringUtils.isEmpty(t.getRefundPassword())) {
                        ajaxResult.setSuccess(false);
                        ajaxResult.setDescription("原密码错误!");
                        return ajaxResult;
                    }
                    boolean isEquals = PasswordUtils.validatePassword(old, t.getRefundPassword());
                    if (!isEquals) {
                        ajaxResult.setSuccess(false);
                        ajaxResult.setDescription("原密码错误!");
                        return ajaxResult;
                    }
                }
                // 两次密码是否一致
                if (!updateRefundPwdInput.getNewPassword().equals(updateRefundPwdInput.getConfirmPassword())) {
                    ajaxResult.setSuccess(false);
                    ajaxResult.setDescription("两次密码输入不一致");
                    return ajaxResult;
                }
                String encryptPassword = PasswordUtils.encryptPassword(updateRefundPwdInput.getConfirmPassword());
                t.setRefundPassword(encryptPassword);
                memberGroupService.update(t);

                ajaxResult.setSuccess(true);
                return ajaxResult;
            }
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("用户id为空");
            return ajaxResult;
        } catch (Exception e) {
            logger.error("修改退款密码异常", e);
            return new AjaxResult(false);
        }
    }

    /**
     * 绑定手机号码
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/bindPhone")
    public AjaxResult bindPhone(MemberGroup member, @Validated VerifyCodeInput verifyCodeInput, BindingResult result) {
        try {

            //数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                return AjaxResult.error(description);
            }

            //加短信开关
            boolean isVerify = sysConfigService.isVerifySms();
            if (isVerify) {
                //验证验证码是否一致
                String code = stringJedis.getValue(verifyCodeInput.getPhone());
                if (!code.equals(verifyCodeInput.getVerifyCode())) {
                    return AjaxResult.error("手机号验证码不一致");
                }
            }
            if (StringUtils.isNotEmpty(member.getId())) {
                MemberGroup t = memberGroupService.get(member.getId());

                if (StringUtils.isNotEmpty(verifyCodeInput.getPhone())) {
                    t.setMobile(verifyCodeInput.getPhone());
                    memberGroupService.update(t);
                }
            }
        } catch (Exception e) {
            logger.error("绑定手机异常", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 新增/编辑
     *
     * @return
     */
    @RequestMapping(value = "system/member/memberForm")
    public ModelAndView memberForm() {
        ModelAndView mv = new ModelAndView("system/member/memberForm");
        MemberGroup member = RealmUtils.getCurrentUser();
        member = memberGroupService.get(member.getId());
        mv.addObject("member", member);

        MemberPartner dbmMemberPartner = memberPartnerService.findByMemberId(member.getId());
        if (null != dbmMemberPartner) {
            mv.addObject("partnerType", dbmMemberPartner.getPartnerType());
        }

        MemberBank account = memberBankService.findByMemberId(member.getId());
        mv.addObject("account", account);
        return mv;
    }

    @ResponseBody
    @RequestMapping("system/member/savePartner")
    public AjaxResult savePartner(MemberGroup member) {
        try {
            memberGroupBizService.savePartnerBiz(member);
        } catch (Exception e) {
            logger.error("用户保存异常", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 修改密码
     *
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/updatePwd")
    public AjaxResult updatePwd(MemberGroup member) {
        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                MemberGroup t = memberGroupService.get(member.getId());

                if (StringUtils.isNotEmpty(member.getPassword())) {
                    String encryptPassword = PasswordUtils.encryptPassword(member.getPassword());
                    t.setPassword(encryptPassword);
                    memberGroupService.update(t);
                }
            }
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return new AjaxResult(false);
        }
        return new AjaxResult(true);
    }

    /**
     * 验证用户名或者手机号
     *
     * @param userId
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping("member/group/checkUniqueProperty")
    public AjaxResult checkUniqueProperty(String key, String value, String userId, Integer type, String roleName) {
        if (StringUtils.isEmpty(key)) {
            return AjaxResult.error("请选择验证用户名或是手机号");
        }
        if (StringUtils.isEmpty(value)) {
            return AjaxResult.error("请输入需要验证的值");
        }
        if ("mobile".equals(key) && null == type) {
            return AjaxResult.error("用户类型不能为空");
        }
        try {
            List<MemberGroup> members = memberGroupService.checkUserName(key, value, userId, type);
            if (members.size() > 0) {
                if (StringUtils.isNotEmpty(userId)) {
                    return AjaxResult.success(false);
                }
                if (StringUtils.isNotEmpty(roleName) && members.size() == 1) {
                    boolean hasPartner = sysRoleService.hasRole(members.get(0).getId(), roleName);
                    if (hasPartner) {
                        return AjaxResult.success(false);
                    } else {
                        return AjaxResult.success(true);
                    }
                }
                return AjaxResult.success(false);
            }
            return AjaxResult.success(true);
        } catch (Exception e) {
            logger.error("验证用户名或手机号异常", e);
            return AjaxResult.error("验证用户名或手机号异常");
        }
    }

    /**
     * 验证用户密码
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/checkPassword")
    public boolean checkPassword(String password, String userId) {
        MemberGroup member = memberGroupService.get(userId);
        return PasswordUtils.validatePassword(password, member.getPassword());
    }

    /**
     * 密码
     *
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/verifyRefundPwd")
    public boolean verifyRefundPwd(String password) {
        MemberGroup m = memberGroupService.getPartner(RealmUtils.getCurrentUser().getId());
        return PasswordUtils.validatePassword(password, m.getRefundPassword());
    }

    /**
     * 保存配置
     *
     * @param packageCount
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/saveSettings")
    public AjaxResult savePackageCount(PackageCount packageCount) {
        if (StringUtils.isEmpty(packageCount.getType())) {
            return AjaxResult.error("配置类型不能为空");
        }
        try {
            savePackageCountBiz.savePackageCountBiz(packageCount);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("保存配置异常");
        }
    }

    /**
     * 查询是否有退款密码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/haveRefundPassword")
    public AjaxResult haveRefundPassword() {
        AjaxResult r = new AjaxResult();
        MemberGroup m = memberGroupService.getPartner(RealmUtils.getCurrentUser().getId());
        if (StringUtils.isEmpty(m.getRefundPassword())) {
            r.setSuccess(false);
        } else {
            r.setSuccess(true);
        }
        return r;
    }

    /**
     * 设置退款密码
     *
     * @param rfp
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/setRefundPassword")
    public AjaxResult setRefundPassword(String rfp) {
        if (StringUtils.isEmpty(rfp)) {
            return AjaxResult.error("参数不能为空");
        }
        AjaxResult r = new AjaxResult();
        String memberId = RealmUtils.getCurrentUser().getId();
        MemberGroup m = memberGroupService.getPartner(memberId);
        if (StringUtils.isEmpty(m.getRefundPassword())) {
            r.setSuccess(true);
            m.setRefundPassword(PasswordUtils.encryptPassword(rfp));
            memberGroupService.update(m);
        } else {
            r.setSuccess(false);
            r.setDescription("退款密码已经存在");
        }
        return r;
    }

    @ResponseBody
    @RequestMapping("system/member/expireCheck")
    public AjaxResult expireCheck() {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String memberId = memberGroupService.getPartnerId(currentUser.getId());
        try {
            String key = "EXPIRE_DATE_" + memberId;
            String value = stringJedis.getValue(key);

            Date date = null;
            if (StringUtils.isNotEmpty(value)) {
                try {
                    date = DateUtils.parse(value, "yyyy-MM-dd HH:mm:ss");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (null == date) {
                date = MemberFormUtil.getExpirationTimeById(memberId);
                if (null == date) {
                    throw new Exception();
                }
                stringJedis.setValue(key, DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("isExpire", MemberFormUtil.isExpire(memberId, date));
            map.put("isChild", currentUser.isChild());
            return AjaxResult.success(map);
        } catch (Exception e) {
            logger.error("获取过期时间异常：memberId-{}", memberId);
            return AjaxResult.success(false);
        }
    }

    /**
     * 保存合作商提现账号
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("system/member/savePartnerAccount")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult savePartnerAccount(MemberBank bank) {
        try {
            if (bank.getMemberId().isEmpty()) {
                return AjaxResult.error("会员ID为空");
            }
            if (StringUtils.isEmpty(bank.getId())) {
                memberBankService.insert(bank);
            } else {//修改合作商提现账号
                memberBankService.update(bank);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("合作商提现账号保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("合作商提现账号保存异常");
        }
    }


    /**
     * 跳转至 分配角色
     *
     * @param
     * @return
     */
    @RequestMapping(value = "system/role/distributionRole")
    public ModelAndView distributionRole(String memberId, String identity, Integer type,
                                         String partnerId, Boolean isNew, Integer typeId) {
        ModelAndView mv = new ModelAndView("system/memberGroup/distributionRole");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
        // 用户已有的角色
        List<SysRole> myRoles = sysRoleService.findByMemberId(memberId);
        List<String> myRoleIds = LangUtils.transform(myRoles, input -> input.getId());
        mv.addObject("myRoleIds", myRoleIds);
        mv.addObject("myRoleIdsJson", JSONArray.toJSONString(myRoleIds));

        if (org.apache.commons.lang3.StringUtils.isEmpty(partnerId)) {
            Map<String, List<SysRole>> systemMap = roleBizService.toAssignRole(identity, type);
            mv.addObject("sysRoles", systemMap);
        } else if (null != typeId) {
            if (new Integer(1).equals(typeId)) {   //一级子账号查父级已有的角色
                // 父级已有的角色
                Map<String, List<SysRole>> partnerRoleMap = Maps.newHashMap();
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(partnerId)) {
                    List<SysRole> partnerRoles = sysRoleService.findByMemberId(partnerId);
                    for (SysRole myRole : partnerRoles) {
                        if (RoleType.SYSTEM_ROLE.getCode().equals(myRole.getType())) {
                            continue;
                        }
                        String roleTypeName = RoleType.getValue(myRole.getType());
                        List<SysRole> sysRoles = partnerRoleMap.get(roleTypeName);
                        if (null == sysRoles) {
                            sysRoles = Lists.newArrayList();
                        }
                        if (sysRoles.size() == 0) {
                            sysRoles.add(myRole);
                        } else {
                            boolean contains = sysRoles.contains(myRole);
                            if (!contains) {
                                sysRoles.add(myRole);
                            }
                        }

                        partnerRoleMap.put(roleTypeName, sysRoles);
                    }

//					SysRole partnerRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
//					SysRole cosponsorRole = sysRoleService.getRole(RoleEnum.COSPONSOR_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
//					List<SysRole> sysRoles = Lists.newArrayList();
//					sysRoles.add(partnerRole);
//					sysRoles.add(cosponsorRole);
//					partnerRoleMap.put(RoleType.SYSTEM_ROLE.getValue(), sysRoles);
                }

                mv.addObject("sysRoles", partnerRoleMap);
            } else if (new Integer(2).equals(typeId)) {  //二级查行知公社管理角色
                SysRole sysRole = new SysRole();
                sysRole.setType(RoleType.KNOWLEDGE_MANAGEMENT_ROLE.getCode());
                sysRole.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                List<SysRole> sysRoles = sysRoleService.list(sysRole);

                //只有行知公社才能分配分管理事长和分管秘书长角色
                if (!xzgsMemberId.equals(currentUser.getId())) {
                    Iterator<SysRole> sysRoleIterator = sysRoles.iterator();
                    while (sysRoleIterator.hasNext()) {
                        SysRole role = sysRoleIterator.next();
                        if (RoleEnum.XZGS_ADMIN.getCode().equals(role.getCode()) ||
                                RoleEnum.BRANCH_MANAGER.getCode().equals(role.getCode())) {
                            sysRoleIterator.remove();
                        }
                    }
                }

                HashMap<String, List<SysRole>> mapSysRoles = Maps.newHashMap();
                mapSysRoles.put(RoleType.KNOWLEDGE_MANAGEMENT_ROLE.getValue(), sysRoles);
                mv.addObject("sysRoles", mapSysRoles);
            }
        }
        mv.addObject("memberId", memberId);
        mv.addObject("isNew", isNew);
        return mv;
    }

    /**
     * 保存分配角色
     *
     * @param memberId
     * @param roleIds
     * @return
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "system/role/saveDistributionRole")
    public AjaxResult saveDistributionRole(String memberId, String roleIds, Boolean isNew) {
        try {
            if (null == isNew) {
                isNew = false;
            }
            if (isNew) {
                roleBizService.assignRoleMemberGroup(roleIds, memberId);
            } else {
                roleBizService.assignRole(roleIds, memberId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分配角色异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存失败");
        }
    }

    /**
     * 获取分社
     *
     * @param memberInput
     * @param page
     * @returns
     */
    @RequestMapping(value = "member/group/selectMember")
    public ModelAndView selectMember(SelectMemberInput memberInput, Page page) {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String memberId = memberGroupService.getPartnerId(currentUser.getId());
        List<MemberGroupOutput> memberList = Lists.newArrayList();

        MemberGroup memberGroup = new MemberGroup();
        memberGroup.setRealname(memberInput.getRealname());
        memberGroup.setUsername(memberInput.getUsername());
        memberGroup.setMobile(memberInput.getMobile());
        memberGroup.setDelFlag(BaseModel.DEL_FLAG_NORMAL);

        memberGroup.setIsPartner(1);
        memberGroup.setIsAdmin(memberInput.getIsAdmin());

        Map<String, Object> params = Maps.newHashMap();
        params.put("partnerId", memberId);

        memberList = memberGroupService.childListPage(memberGroup, params, page);
        ModelAndView mv = new ModelAndView("/member/selectMember");
        mv.addObject("page", page);
        mv.addObject("memberInput", memberInput);
        mv.addObject("memberList", memberList);
        return mv;
    }


    /**
     * 跳转至 分配分社
     *
     * @return
     */
    @RequestMapping(value = "member/group/adminAuth")
    public ModelAndView adminAuth(String adminId) {
        ModelAndView mv = new ModelAndView("/system/memberGroup/adminAuth");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        // 分社列表
        List<MemberGroup> memberGroups = memberGroupService.getChildList(currentUser.getId());
        mv.addObject("memberGroups", memberGroups);

        //该管理员下的分社列表
        CAdminBranch cAdminBranch = new CAdminBranch();
        cAdminBranch.setAdminId(adminId);
        List<CAdminBranch> myMemberGroups = adminBranchService.list(cAdminBranch);

        mv.addObject("myMemberGroups", myMemberGroups);
        mv.addObject("adminId", adminId);
        return mv;
    }

    /**
     * 保存 管理员分社关系
     *
     * @param adminId
     * @param memberGroupIds
     * @return
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "member/group/saveAdminAuth")
    public AjaxResult saveAdminAuth(String adminId, String memberGroupIds) {
        if (StringUtils.isEmpty(adminId)) {
            return AjaxResult.error("adminId不能为空");
        }
        try {
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();

            CAdminBranch query = new CAdminBranch();
            query.setAdminId(adminId);
            List<CAdminBranch> list = adminBranchService.list(query);

            for (CAdminBranch cabobj : list) {
                adminBranchService.delete(cabobj.getId());
            }
            if (StringUtils.isNotEmpty(memberGroupIds)) {
                for (String membergroupId : memberGroupIds.split(",")) {
                    CAdminBranch cAdminBranch = new CAdminBranch();
                    cAdminBranch.setAdminId(adminId);
                    cAdminBranch.setBranchId(membergroupId);
                    cAdminBranch.setCreateBy(currentUser.getId());
                    cAdminBranch.setUpdateBy(currentUser.getId());
                    adminBranchService.insert(cAdminBranch);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "error");
        }
        return new AjaxResult(true, "success");
    }
}
